<?
require_once("../classes/database.php");
function getDatas($path = "../pictures/news/"){
	//Đọc URI
	$file_name = @$_SERVER['REQUEST_URI'];
	
	if($file_name == ""){
		exit();
	}
	
	//Bẻ dấu / cuối cùng để lấy file name
	$file_name = explode("/", $file_name);
	$file_name = $file_name[count($file_name) - 1];
	
	$allow_list = "jpg,jpeg,gif,png,jpe,swf";
	//Kiểm tra đuôi nếu không hợp lệ thì deny
	if (check_extension($file_name,$allow_list) != 1){
		echo "Access deny";
		return;
	}

	$file_name	= str_replace("\'", "'", $file_name);
	$file_name	= str_replace("'", "''", $file_name);
	//lay tu database ra
	$db_image = new db_query("SELECT pic_source 
										FROM pictures
										WHERE pic_name = '" . $file_name . "'
										LIMIT 1");
	if($row = mysql_fetch_assoc($db_image->result)){
		
		$link = str_replace(" ","%20",$row["pic_source"]);
		//echo $link; exit();
		//Thử lấy từ vatgia.com
		if ($mycontent = @file_get_contents($link)){
			//Chống lỗi ghi file do nhiều request cùng lúc
			if (!file_exists($path . $file_name)){
				@file_put_contents($path . $file_name, $mycontent);
			}
			//Save vào 1 file khác là URL decode
			if (urldecode($file_name) != $file_name){
				@file_put_contents($path . urldecode($file_name), $mycontent);
			}
			//In ra màn hình
			echo $mycontent;
			
			$db_exe	=	new db_execute("DELETE FROM pictures WHERE pic_name = '" . $file_name . "' LIMIT 1");
			
			return;
		}
		else{
			echo "404 - File not found";
		}
	}
}

function getExtension($filename){
	
	$sExtension = substr($filename, (strrpos($filename, ".") + 1));
	
	if(strlen($sExtension) > 4){
		$info	=	getimagesize($filename);
		if(isset($info['mime'])){
			switch($info['mime']){
				case "image/jpeg":
					$sExtension	=	"jpg"; break;
				case "image/gif":
					$sExtension	=	"gif"; break;
				case "image/png":
					$sExtension	=	"png"; break;
				default:
					$sExtension	=	"jpg"; break;
			}
		}
	}
	
	$sExtension = strtolower($sExtension);
	
	return $sExtension;
}

function check_extension($filename, $allow_list){
	
	$sExtension =	getExtension($filename);
	
	$allow_arr = explode(",", $allow_list);
	$pass = 0;
	
	if(in_array($sExtension, $allow_arr)){
		$pass	=	1;
	}
	
	return $pass;
}
?>